<template>
  <div class="show-dormitory">
    <DormitoryDetailsHeader
      :details="dormitoryDetails"
      :details-data="dormitoryDetailsData"
    />

    <div class="room__list">
      <el-button type="primary" @click="drawerClick"> 添加房间 </el-button>
      <ShowItem :table-data="roomInfo" @onDetRooms="handleDetRooms" @onEditRooms="handleEditRoom" />
      <div style="display: flex; justify-content: end;">
        <Pagination
          style="background-color:transparent; padding: 0;margin-top: 20px;"
          :total="roomTotal"
          :limit="page.pageSize"
          @pagination="handlePageChange"
        />
      </div>

    </div>
    <AddRoom :id="id" ref="addRoom" />
    <EditRoom
      v-model="editRoomDialog.visible"
      :room="editRoomDialog.room"
      :user-number="userNumber"
      @success="handleUpdateSuccess"
      @failed="handleUpdateFailed"
    />
  </div>
</template>
<script>
import { rooms, dormitory } from '@/api/v2/dorm'
import { deleteRoom } from '@/api/dorm'
import ShowItem from './ShowItem.vue'
import AddRoom from './AddRoom.vue'
import EditRoom from './components/EditRoom'
import Pagination from '@/components/Pagination/index.vue'
import DormitoryDetailsHeader from '@/views/dormitory/components/Header/Header.vue'
export default {
  components: {
    ShowItem,
    AddRoom,
    Pagination,
    EditRoom,
    DormitoryDetailsHeader
  },
  data() {
    return {
      id: '',
      room: [],
      roomInfo: [],
      tableData: [],
      photoInfo: [],
      dormitoryDetails: null,
      roomTotal: 0,
      page: {
        currentPage: 1,
        pageSize: 10
      },
      editRoomDialog: {
        visible: false,
        room: null
      },
      loadingStatuses: {
        loading: false
      },
      userNumber: 0
    }
  },
  computed: {
    dormitoryDetailsData() {
      return [
        { title: '可住房间', icon: 'livable', value: this.dormitoryDetails?.available_room },
        { title: '空房间', icon: 'spare_room', value: this.dormitoryDetails?.available_room },
        { title: '房间总数', icon: 'room_count', value: this.dormitoryDetails?.room_count }
      ]
    }
  },
  created() {
    this.id = this.$route.params?.id
    console.log('id', this.id)
    // this.getRoomInfo();
    this.getDormDetails()
    this.getDormitoryTheRooms()
    // dormitory(this.id)
    //   .then((res) => {
    //     console.log(res,'11')
    //     this.room = res.data
    //     this.roomInfo = res.data.room
    //     // this.tableData = this.roomInfo
    //     //   .filter(item => item.userCompany.length > 0)
    //     //   .flatMap(item => item.userCompany.map(user => ({
    //     //     userName: user.user.username,
    //     //     roomName: item.name,
    //     //     roonRent: this.room.rent,
    //     //     userID: user.user.id
    //     //   })))
    //     this.photoInfo = JSON.parse(res.data.photo)
    //   })

    //   .catch((err) => {
    //     console.log(err)
    //   })
  },
  methods: {
    drawerClick() {
      this.$refs.addRoom.visible = true
      this.$nextTick(() => {
        this.$refs.addRoom.resetForm('ruleForm')
      })
    },
    async getDormDetails() {
      try {
        const res = await dormitory(this.id)
        console.log('res --------->', res)
        this.dormitoryDetails = res.data
        this.photoInfo = res.data.photo ? JSON.parse(res.data.photo) : []
      } catch (error) {
        this.$messages.error('获取信息失败')
      }
    },
    async getDormitoryTheRooms() {
      const params = {
        paginate: this.page.pageSize,
        page: this.page.currentPage,
        dormitory_id: this.id
      }
      try {
        const { data, meta: { total }} = await rooms(params)
        // if (this.room.length >= 2) {
        //   this.room = []
        // }
        // this.room = []
        // this.room.push({ label: '当前房间数', value: total },
        //   { label: '剩余可住的房间数', value: data
        //     .filter(item => item.number !== item.fieldData?.length).length }
        // )
        // console.log(this.room, 'room')
        this.roomTotal = total
        this.roomInfo = data.map(item => {
          return {
            ...item,
            photo: item.photo ? JSON.parse(item.photo) : ''
          }
        })
        console.log(this.roomInfo, 'getDormitoryTheRooms')
      } catch (error) {
        console.log(error, 'error')
      }
    },
    handlePageChange(e) {
      console.log(e, 'e')
      this.page.currentPage = e.page
      this.page.pageSize = e.limit
      this.getDormitoryTheRooms()
    },
    async handleDetRooms(id) {
      try {
        await deleteRoom(id)
        this.getDormitoryTheRooms()
        this.$message.success('删除成功')
      } catch (error) {
        this.$message.error(error.response?.data?.message || '删除失败')
      }
    },
    handleEditRoom(room) {
      const { dormitory, name, number, rent, remark, photo, id, fieldData } = room
      this.userNumber = Number(fieldData.length)
      this.editRoomDialog.room = {
        apartmentID: dormitory.id,
        id,
        roomName: name,
        bad: Number(number),
        rent: Number(rent),
        remark,
        photos: photo
      }
      console.log(this.editRoomDialog.room, 'editRoomDialog')
      this.editRoomDialog.visible = true
    },
    // 修改事件结果
    handleUpdateSuccess(result) {
      this.$message.success(result.message ?? '修改成功')
      this.editRoomDialog.visible = false
      this.refreshTable()
    },
    async refreshTable() {
      try {
        if (this.loadingStatuses.loading) return
        this.loadingStatuses.loading = true
        await this.sleep(400)
        await this.loadData()
      } catch (e) {
        console.log(e, 'e')
      } finally {
        this.loadingStatuses.loading = false
      }
    },
    sleep(t) {
      return new Promise((r) => setTimeout(r, t))
    },
    async loadData() {
      const result = await Promise.allSettled([this.getDormitoryTheRooms()])

      const failTasks = result.filter((item) => item.status === 'rejected')
      if (failTasks.length <= 0) return
      throw failTasks.at(0)
    },
    async getRooms() {
      // const { size, current } = this.pagination

      // const { name, dormitory_id, minrent, maxrent, username, number } =
      //   this.form

      // const params = {
      //   paginate: size,
      //   page: current,
      //   name: name,
      //   dormitory_id: dormitory_id,
      //   minrent: minrent,
      //   maxrent: maxrent,
      //   username: username,
      //   number: number
      // }
      // const result = await rooms(params)
      // this.rooms = result?.data ?? []
      // this.pagination.total = result?.meta?.total ?? 0
    },
    handleUpdateFailed(e) {
      this.$message.error(e.message ?? '修改失败')
    },

    refresh() {
      this.refreshTable()
      this.getDormitoryTheRooms()
      this.getDormDetails()
    }
  }
}
</script>

<style lang="scss" scoped>
* {
  font-family: Microsoft YaHei, Microsoft YaHei;
}
.show-dormitory {
  padding: 20px;
  .el-button {
    margin-bottom: 20px;
  }
  &-item {
    display: flex;
    margin-left: 40px;
    margin-top: 20px;
    &-title {
      display: flex;
      align-items: center;
      margin-right: 120px;
      span {
        color: #8e8e8e;
        padding-right: 40px;
      }
    }
  }
  &-photo {
    display: flex;
    align-items: center;
    margin-left: 40px;
    span {
      color: #8e8e8e;
      padding-right: 40px;
    }
    .roomPhoto {
      padding-right: 10px;
      width: 60px;
      height: 60px;
      .el-image {
        width: 100%;
        height: 100%;
      }
    }
  }

  .room__list {
    padding: 20px;
    background: #fff;
    border-radius: 4px;
  }
}
</style>
